package me.shurufa.adapter;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

import me.shurufa.R;
import me.shurufa.bean.Book;
import me.shurufa.holder.MostDigestViewHolder;
import me.shurufa.implement.BookLongClickListener;
import me.shurufa.utils.Global;
import me.shurufa.utils.Utils;

/**
 * Create by andy (https://github.com/andyxialm)
 * Create time: 16/5/9 09:36
 * Description : 发现模块适配器
 */
public class MostDigestAdapter extends RecyclerView.Adapter<MostDigestViewHolder> {

    private List<Book> dataList;
    private Object parent;
    private BookLongClickListener listener;
    private int mWhereFrom;

    public void setBookLongClickListener(BookLongClickListener listener){
        this.listener = listener;
    }

    public MostDigestAdapter(Object parent, List<Book> dataList) {
        this.dataList = dataList;
        this.parent = parent;
    }

    public MostDigestAdapter(Object parent, List<Book> dataList, int fromWhere) {
        this.dataList = dataList;
        this.parent = parent;
        mWhereFrom = fromWhere;
    }

    @Override
    public MostDigestViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_item_shelves_book, parent, false);
        // TODO: 16/3/8 Debug测试用  原来的 TYPE_FROM_MY_BOOKSHELVES
        MostDigestViewHolder holder = new MostDigestViewHolder(v, parent, mWhereFrom,
                Global.getCurrentUid(), listener);
        return holder;
    }

    @Override
    public void onBindViewHolder(MostDigestViewHolder holder, int position) {
        try {
            Book book = dataList.get(position);
            holder.bind(book);
        } catch (Exception e) {
        }
    }

    @Override
    public void setHasStableIds(boolean hasStableIds) {
        super.setHasStableIds(hasStableIds);
    }

    /**
     * 添加数据在尾部
     * @param items
     */
    public void append(List<Book> items) {
        if (Utils.isNullForList(items)) {
            return;
        }
        int pos = dataList.size();
        dataList.addAll(items);
        notifyItemRangeInserted(pos, items.size());
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }

    public void remove(int position) {
        if (dataList.size() > 0) {
            dataList.remove(position);
            this.notifyItemRemoved(position);
        }
    }

    public void clear() {
        int size = dataList.size();
        dataList.clear();
        this.notifyItemRangeRemoved(0, size);
    }
}
